package com.jjiang.bbmall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.jjiang.bbmall.ware.feign.MemberFeignService;
import com.jjiang.bbmall.ware.vo.FareResponseVo;
import com.jjiang.bbmall.ware.vo.MemberReceiveAddressVo;
import com.jjiang.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjiang.common.utils.PageUtils;
import com.jjiang.common.utils.Query;

import com.jjiang.bbmall.ware.dao.WareInfoDao;
import com.jjiang.bbmall.ware.entity.WareInfoEntity;
import com.jjiang.bbmall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareInfoEntity> wareInfoEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wareInfoEntityQueryWrapper.eq("id", key).or()
                    .like("name", key)
                    .or().like("address", key)
                    .or().like("areacode", key);
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wareInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FareResponseVo getFare(Long addrId) {
        FareResponseVo fareResponseVo = new FareResponseVo();
        R r = memberFeignService.info(addrId);
        if (r.getCode() == 0) {
            MemberReceiveAddressVo memberReceiveAddress = r.getData("memberReceiveAddress", new TypeReference<MemberReceiveAddressVo>() {
            });
            if (memberReceiveAddress != null) {
                // 计算运费
                String phone = memberReceiveAddress.getPhone();
                String fareString = phone.substring(phone.length() - 1);
                BigDecimal fare = new BigDecimal(fareString);
                fareResponseVo.setAddress(memberReceiveAddress);
                fareResponseVo.setFare(fare);
            }
        }
        return fareResponseVo;
    }
}
